package com.atguigu.srb.core.controller.api;


import com.atguigu.srb.base.config.JwtUtils;
import com.atguigu.srb.commom.exception.Assert;
import com.atguigu.srb.commom.result.R;
import com.atguigu.srb.commom.result.ResponseEnum;
import com.atguigu.srb.commom.untis.RegexValidateUtils;
import com.atguigu.srb.core.Vo.LoginVo;
import com.atguigu.srb.core.Vo.RegisterVO;
import com.atguigu.srb.core.Vo.UserInfoVo;
import com.atguigu.srb.core.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户基本信息 前端控制器
 * </p>
 *
 * @author lay_hu
 * @since 2021-12-13
 */
@Api(tags = "会员接口")
@RestController
@RequestMapping("/api/core/userInfo")
@Slf4j
//@CrossOrigin
public class UserInfoController {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    UserInfoService userInfoService;
    @PostMapping("/register")
    public R register(@RequestBody RegisterVO registerVO){
        String codeGen= registerVO.getCode();
        String mobile = registerVO.getMobile();
        String password = registerVO.getPassword();
        Assert.notEmpty(codeGen,ResponseEnum.CODE_NULL_ERROR);
        Assert.notEmpty(mobile,ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(password,ResponseEnum.PASSWORD_NULL_ERROR);
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile),ResponseEnum.MOBILE_ERROR);
        String code=(String) redisTemplate.opsForValue().get("srb:sms:code"+mobile);
        userInfoService.register(registerVO);
        //验证码校验
        Assert.equals(codeGen,code, ResponseEnum.CODE_ERROR);

        return  R.ok().message("注册成功");

    }
    @ApiOperation("会员登录")
    @PostMapping("/login")
    public  R login(@RequestBody LoginVo loginVo, HttpServletRequest request){
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        Assert.notEmpty(mobile,ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(password,ResponseEnum.PASSWORD_NULL_ERROR);
        String ip = request.getRemoteAddr();
      UserInfoVo userInfoVo= userInfoService.login(loginVo,ip);
      return  R.ok().data("userInfoVo",userInfoVo).message("登录成功");
    }
    @ApiOperation("校验令牌")
    @GetMapping("/checkToken")
    public R checkToken(HttpServletRequest request) {

        String token = request.getHeader("token");
        boolean result = JwtUtils.checkToken(token);

        if(result){
            return R.ok();
        }else{
            //LOGIN_AUTH_ERROR(-211, "未登录"),
            return R.setResult(ResponseEnum.LOGIN_AUTH_ERROR);
        }
    }
    @ApiOperation("手机号码得校验")
    @GetMapping("/checkMobile/{mobile}")
    public  boolean checkMobile(@PathVariable String mobile){

       return  userInfoService.checkmobile(mobile);

    }


}

